package cn.bxshey.gateway.filter;

import cn.bxshey.general.constant.JwtConstant;
import cn.bxshey.general.enums.HeaderEnum;
import cn.bxshey.general.util.JwtUtils;
import com.alibaba.fastjson.JSON;
import cn.bxshey.general.Result.Result;
import cn.bxshey.general.enums.ResultEnum;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @作者:不想说话而已
 * @Date:2023/11/23 20:53 周四
 */

@Component
public class CustomizeGlobalFilter implements GlobalFilter, Ordered {


    private static final String AUTH = "authentication"; //需要认证的请求路径所含的标识

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //获取http请求信息
        ServerHttpRequest request = exchange.getRequest();
        Map<String, Object> tokenInfo = new HashMap<>();

        //获取请求访问路径，判断该访问路径是否需要权限校验
        RequestPath path = request.getPath();
        if (String.valueOf(path).contains(AUTH)) {
            //需要鉴权，获取请求token
            HttpHeaders headers = request.getHeaders();
            List<String> list = headers.get(JwtConstant.ACCESS_TOKENS); //获取请求头token

            if (Objects.isNull(list)) {
                //没有令牌，返回JSON格式的错误信息
                return buildReturnMono(ResultEnum.ERROR_LOGIN, exchange);
            }

            //对token进行解析，失败则返回错误信息，拦截请求
            Map<String, Object> info = JwtUtils.checkToken(list.get(0));
            if (Objects.isNull(info)) {
                return buildReturnMono(ResultEnum.ERROR_AUTH, exchange); //JSON格式的错误信息
            }

        }

       //清除掉内部远程调用的验证的指定标识头
        request.mutate().headers(s->{
            s.remove(HeaderEnum.HEADER_FEIGN.key);
        }).build();

        //不需要校验则放行
        return chain.filter(exchange);

    }

    //返回JSON格式的错误信息
    private Mono<Void> buildReturnMono(ResultEnum resultEnum, ServerWebExchange exchange) {
        ServerHttpResponse response = exchange.getResponse(); //返回的请求信息
        String jsonString = JSON.toJSONString(Result.error(resultEnum)); //需要返回错误的信息内容
        byte[] bits = jsonString.getBytes(StandardCharsets.UTF_8); //设置字符集
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        //设置请求头
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }


    //过滤器优先级，值越小优先级越高
    @Override
    public int getOrder() {
        return -1;
    }
}
